package com.afei.java.ai.langchain4j.store;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * @Title: MongoChatMemoryStore
 * @Author wangyf
 * @Package com.afei.java.ai.langchain4j.store
 * @Date 2025/4/24 15:31
 * @description: 实现记忆持久化的类
 */

@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        com.afei.java.ai.langchain4j.bean.ChatMessage chatMessage = mongoTemplate.findOne(query, com.afei.java.ai.langchain4j.bean.ChatMessage.class);

        if (chatMessage == null) {
            return new LinkedList<>();
        }
        String content = chatMessage.getContent();
        return ChatMessageDeserializer.messagesFromJson(content);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        Update update = new Update();


        update.set("content", ChatMessageSerializer.messagesToJson(list));

        mongoTemplate.upsert(query, update, com.afei.java.ai.langchain4j.bean.ChatMessage.class);


    }

    @Override
    public void deleteMessages(Object memoryId) {
        Criteria criteria = Criteria.where("_id").is(memoryId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, com.afei.java.ai.langchain4j.bean.ChatMessage.class);

    }
}
